package com.njupt.Tree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/27 19:05
 * @Description: 572. 另一棵树的子树
 * @Version: 1.0
 */


public class IsSubtree {

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()){
            if(cur != null){
                if(isSame(cur, subRoot)){
                    return true;
                }
                stack.push(cur);
                cur = cur.left;
            }else {
                cur = stack.pop();
                cur =cur.right;
            }
        }

        return false;
    }

    private Boolean isSame(TreeNode cur, TreeNode subRoot) {
        if(cur == null && subRoot != null
                || cur != null && subRoot == null){
            return false;
        } else if (cur == null && subRoot == null) {
            return true;
        } else if (cur.val != subRoot.val) {
            return false;
        }
        Boolean left = isSame(cur.left, subRoot.left);
        Boolean right = isSame(cur.right, subRoot.right);

        return left && right;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(4);
        root.right = new TreeNode(5);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(2);
        root.left.right.left = new TreeNode(0);

        TreeNode subRoot = new TreeNode(4);
        subRoot.left = new TreeNode(1);
        subRoot.right = new TreeNode(2);

        IsSubtree test = new IsSubtree();
        System.out.println(test.isSubtree(root, subRoot));
    }
}
